package com.Policing.Scrap;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Receive.add_recipient;
import com.Policing.Since_case.Since_case;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.Policing.Adapter.Addrepairs_Adapter;
import com.Policing.Shift.Allot_unit;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.bean.AddRepairs_bean;

import com.senter.iot.support.openapi.uhf.UhfD2;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/5/9.
 */

public class Scrap_Add extends Activity implements OnDismissListener {
    private String department_id="",personid="";//部门id
    private TextView person_tv;
    private List<String> rfid_data = new ArrayList<>();
    private TextView title_text,department_tv;//标题，部门，报废人，临时存放
    private LinearLayout department,person;//部门，报废人，临时存放
    private ImageView fh;
    private String url="http://"+ Ip_Set.IP+"/api/scrapAddInspect";
    private String upload_url="http://"+ Ip_Set.IP+"/api/scrapAdd";
    private Handler handler = new Handler();
    private List<String> numbers = new ArrayList<>();//编号集合
    private List<String> remarks = new ArrayList<>();//集合s
    private List<AddRepairs_bean> data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private ListView listView;
    private String id="";

    private EditText et,et_num;
    private Button scan_img,uploading,bt_Rfid;
    private boolean state;
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(Scrap_Add.this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    private boolean isrfid=true;
    private boolean stop_rfid =true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scrap_add);
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        inview();
    }

    private void inview() {
        et_num = (EditText) findViewById(R.id.et_num);
        et_num.setInputType(InputType.TYPE_NULL);
        et_num.requestFocus();
        person = (LinearLayout) findViewById(R.id.person);
        bt_Rfid = (Button) findViewById(R.id.Rfid);
      /*  fold = (TextView) findViewById(R.id.fold);
        fold_unit = (LinearLayout) findViewById(R.id.fold_unit);*/
        uploading = (Button) findViewById(R.id.upload);
        listView = (ListView) findViewById(R.id.fragment2_list);
        scan_img = (Button) findViewById(R.id.scan_img);
        department_tv = (TextView) findViewById(R.id.department_tv);
        person_tv = (TextView) findViewById(R.id.person_tv);
        et = (EditText) findViewById(R.id.remark);
        department = (LinearLayout) findViewById(R.id.department);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("新建报废单");
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
      /*  fold_unit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                department_tv.setText("");
                department_id="";
                personid="";
                person_tv.setText("");
                Intent dept = new Intent(Scrap_Add.this, Allot_unit.class);
                dept.putExtra("status","1");
                startActivityForResult(dept, 1);
            }
        });*/
        et_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_num.selectAll();
            }
        });
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i=0;i<data.size();i++){
                    if (S.equals(data.get(i).getCode_number())){
                        Toast.makeText(Scrap_Add.this,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                if (!et_num.getText().toString().trim().equals("")){
                    if (!lv_data.contains(et_num.getText().toString().trim())){
                        upload(et_num.getText().toString().trim(),"");
                    }else {
                        Toast.makeText(Scrap_Add.this,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(Scrap_Add.this,"错误的格式",Toast.LENGTH_SHORT).show();
                }
            }
        });
        department.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*if (!fold.getText().toString().equals("")){ }*/
                    person_tv.setText("");
                    personid = "";
                    Intent intent = new Intent(Scrap_Add.this, Allot_unit.class);
                    intent.putExtra("status", "2");
                    startActivityForResult(intent,2);

            }
        });
        person.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!department_tv.getText().toString().equals("")) {
                    Intent intent = new Intent(Scrap_Add.this, add_recipient.class);
                    intent.putExtra("department_id", department_id);
                    startActivityForResult(intent,2);

                }
            }
        });
        //扫二维码
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int i, long id) {
                new AlertView(" 提示！", "是否删除", "取消",new String[]{"确定"}, null, Scrap_Add.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            for (int j=0;j<lv_data.size();j++){
                                if (lv_data.get(j).equals(data.get(i).getCode_number())){
                                    lv_data.remove(j);
                                }
                            }
                            data.remove(i);
                            Addrepairs_Adapter adapter_item = new Addrepairs_Adapter(Scrap_Add.this,R.layout.addrepairs_item,data);
                            listView.setAdapter(adapter_item);
                        }
                        if (position==-1){
                        }

                    }
                }).setCancelable(true).setOnDismissListener(Scrap_Add.this).show();
            }
        });
        bt_Rfid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (person_tv.getText().toString().trim().equals("")){
                    Toast.makeText(Scrap_Add.this,"请选择报废人后重试",Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    if (isrfid==true){
                        if (UhfD2.getInstance().init() == true){
                            UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                        }
                        isrfid = false;
                    }

                }catch (Exception E){
                    Toast.makeText(Scrap_Add.this,"没有RFID模块",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (stop_rfid){
                    stop_rfid=false;
                    start_read();
                    bt_Rfid.setText("停止读取");
                }else {
                    stop_rfid=true;
                    state =false;
                    bt_Rfid.setText("开启RFID");
                }

            }
        });
        uploading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!department_id.equals("")&&!person_tv.getText().toString().equals("")){
                    if (data.size()>0){

                        new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, Scrap_Add.this, AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                //取消：position=-1,确定 position=0
                                if (position==0){
                                    numbers.clear();
                                    remarks.clear();
                                    for (int i =0;i<data.size();i++){
                                        numbers.add(data.get(i).getCode_number());
                                        remarks.add(data.get(i).getRemark());
                                    }
                                    updata();
                                }
                                if (position==-1){

                                }

                            }
                        }).setCancelable(true).setOnDismissListener(Scrap_Add.this).show();
                    }else {
                        Toast.makeText(Scrap_Add.this,"请扫码添加需报废的资产",Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(Scrap_Add.this,"请完善数据重试",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void updata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumbers",numbers.toString())
                        .add("deptId",department_id)
                        .add("userId",personid)
                        .add("source",Since_case.set().getSource())
                        .add("operator",id)
                        .add("company","")
                        .add("remark",et.getText().toString())
                        .add("reasons",remarks.toString()); //传递键值对参数
                Log.e("添加报废数据a:0", numbers.toString()+"1"+ department_id+"2"+personid+"3"+id+"4"+et.getText().toString()+"5"+remarks.toString());
                Request request = new Request.Builder()//创建Request 对象。
                        .url(upload_url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject json = new JSONObject(responseData);
                                    if (json.getString("state").equals("1")){
                                        data.clear();
                                        lv_data.clear();
                                        Addrepairs_Adapter adapter_item = new Addrepairs_Adapter(Scrap_Add.this,R.layout.addrepairs_item,data);
                                        listView.setAdapter(adapter_item);
                                        Intent intent = new Intent(Scrap_Add.this,Scrap_dispose.class);
                                        intent.putExtra("scrapId",json.getString("scrapId"));
                                        startActivity(intent);
                                        finish();
                                    }
                                    if (json.getString("state").equals("0")){
                                        Toast.makeText(Scrap_Add.this,"提交失败",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
       /* if (requestCode==1&&resultCode==2){
            fold_id = datas.getExtras().getString("dept_id");
            String name = datas.getExtras().getString("dept_name");
            fold.setText(name);

        }*/
        if (requestCode==2&&resultCode==3){
            person_tv.setText(datas.getExtras().getString("recipient_name"));
            personid = datas.getExtras().getString("recipient_id");
        }
        if (requestCode==2&&resultCode==1){
            department_id = datas.getExtras().getString("dept_id");
            String name = datas.getExtras().getString("dept_name");
            department_tv.setText(name);
            Log.i("333333333333",department_id);
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            final String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            for (int i=0;i<data.size();i++){
                if (scanResult.equals(data.get(i).getCode_number())){
                    Toast.makeText(Scrap_Add.this,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (!lv_data.contains(scanResult)){
                        upload(scanResult,"");
            }else Toast.makeText(Scrap_Add.this,"该资产已存在列表",Toast.LENGTH_SHORT).show();

        }
    }

    private void upload(final String scanResult, final String rfid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber",scanResult)
                        .add("rfid",rfid)
                        .add("source", Since_case.set().getSource())
                        .add("userId",personid); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("123123", responseData);
                                    JSONObject json = new JSONObject(responseData);
                                    Bitmap bitmap =null;
                                    if (json.getString("state").equals("0")){
                                        Toast.makeText(Scrap_Add.this,"失败",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("1")){
                                        lv_data.add(scanResult);
                                        JSONObject jsonObject = json.getJSONObject("asset");
                                        String assetName = jsonObject.getString("assetName");
                                        String deptId = jsonObject.getString("deptId");
                                        String assetNumber = jsonObject.getString("assetNumber");
                                        String userId = jsonObject.getString("userId");
                                        String model = jsonObject.getString("model");
                                      //  String type = jsonObject.getString("type");
                                        //String rfid = jsonObject.getString("rfid");
                                       // String remark = jsonObject.getString("remark");
                                        if (jsonObject.getString("image").equals("")){
                                            /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                            bitmap = BitmapFactory.decodeStream(is);*/
                                        }else {
                                            byte [] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                        }
                                        Collections.reverse(data);
                                        data.add(new AddRepairs_bean(bitmap,assetName,deptId,assetNumber,userId,model,"","","类别",""));
                                        Collections.reverse(data);
                                        Addrepairs_Adapter adapter_item = new Addrepairs_Adapter(Scrap_Add.this,R.layout.addrepairs_item,data);
                                        listView.setAdapter(adapter_item);
                                    }
                                    if (json.getString("state").equals("2")){
                                        Toast.makeText(Scrap_Add.this,"不存在此资产",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("3")){
                                        Toast.makeText(Scrap_Add.this,"此资产已报废",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("4")){
                                        Toast.makeText(Scrap_Add.this,"资产非当前报废人持有，无权报废",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("5")){
                                        Toast.makeText(Scrap_Add.this,"该资产已申请报废",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }



                            }
                        });

                    }
                });

            }
        }).start();
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Scrap_Add.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Scrap_Add.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Scrap_Add.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Scrap_Add.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Scrap_Add.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);//Constant.REQ_QR_CODE=11002
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Scrap_Add.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Scrap_Add.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onDismiss(Object o) {

    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                for (int i = 0; i<data.size();i++){
                    if (DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4).equals(data.get(i).getRfid())){
                        return;
                    }
                }
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    final String rfid = DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            upload("",rfid);


                        }
                    },500);
                    trigTagAccompainiment();//播放声音
                }
            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
}
